#include "an.rpc.h"

#include "../Headers/log.h"
#include "../USS/USSclient.h"
#include "../NS/nameserver.h"

#include <string>
#include <vector>
#include <algorithm>

#include <iostream>

static std::vector<std::string> sessions;

int * login_1_svc(User * user, struct svc_req * svc) {
  static int respond;
  std::string username = user->username;
  std::string password = user->password;
  
  TOB::Log::event("AN: Connecting " + username);

  TOB::US us(static_cast<TOB::Nameserver::IP>(user->nsip));
  std::string USValue;
  
  respond = us.getStringByLogin(username, "password", USValue);
  if(respond == Code::Okay) {
    if(USValue == password) {
      respond = static_cast<int>(Code::Okay);
      if (std::find(sessions.begin(), sessions.end(), username) == sessions.end()) {
        sessions.push_back(username);
      }
    } else {
      respond = (int)Code::AN_PasswordUncorrect;
    }
  }
  
  return &respond;
}

int * logout_1_svc(User * user, struct svc_req * svc) {
  static int respond;
  std::string username = user->username;
  std::string password = user->password;
  
  TOB::Log::event("AN: Disconecting " + username);
  
  TOB::US us(static_cast<TOB::Nameserver::IP>(user->nsip));
  std::string USValue;

  respond = us.getStringByLogin(username, "password", USValue);
  if(respond == Code::Okay) {
    if(USValue == password) {
      respond = static_cast<int>(Code::Okay);
      auto it = std::find(sessions.begin(), sessions.end(), username);
      if (it != sessions.end()) {
        sessions.erase(it);
      }
    } else {
      respond = (int)Code::AN_PasswordUncorrect;
    }
  }
  
  return &respond;
}

int * online_1_svc(User * user, struct svc_req * svc) {
  static int respond;
  std::string username = user->username;
  
  TOB::Log::event("AN: Test " + username);
  
  respond = static_cast<int>(Code::Okay);
  if (std::find(sessions.begin(), sessions.end(), username) == sessions.end()) {
    respond = 1;
  }
  
  return &respond;
}
